package com.lsh.payment.core.strategy.query;

import com.lsh.payment.core.exception.BusinessException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Project Name: lsh-payment
 *
 * @author peter
 * @date 16/11/6
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Component
public class QueryStrategyFactory implements InitializingBean, ApplicationContextAware {

    private static Map<Integer, QueryStrategy> strategyMap = new HashMap<>();

    private ApplicationContext applicationContext;

    private QueryStrategyFactory() {
    }

    @Override
    public void afterPropertiesSet() throws BusinessException {
        Map<String, QueryStrategy> strategyInfos = applicationContext.getBeansOfType(QueryStrategy.class);
        if(CollectionUtils.isEmpty(strategyInfos)) {
            return;
        }

        for(String key : strategyInfos.keySet()) {
            strategyMap.put(strategyInfos.get(key).getStrategyNo(), strategyInfos.get(key));
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    /**
     *
     * @param type
     * @return
     */
    public QueryStrategy creator(Integer type) {
        return strategyMap.get(type);
    }

}
